﻿#region License
// (c) Intergen.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
#endregion

using System;
using System.Collections.Generic;
using System.Collections;

namespace TextGlow.Control.Utilities
{
  public class SmartEnumerable<T> : IEnumerable<Entry<T>>
  {
    IEnumerable<T> _enumerable;

    public SmartEnumerable(IEnumerable<T> enumerable)
    {
      if (enumerable == null)
        throw new ArgumentNullException("enumerable");

      _enumerable = enumerable;
    }

    public IEnumerator<Entry<T>> GetEnumerator()
    {
      using (IEnumerator<T> enumerator = _enumerable.GetEnumerator())
      {
        if (!enumerator.MoveNext())
        {
          yield break;
        }
        bool isFirst = true;
        bool isLast = false;
        int index = 0;

        while (!isLast)
        {
          T current = enumerator.Current;
          isLast = !enumerator.MoveNext();

          Position position = ((index + 1) % 2 == 0) ? Position.Even : Position.Odd;
          if (isFirst)
            position = position | Position.First;
          if (isLast)
            position = position | Position.Last;

          yield return new Entry<T>(current, index, position);

          index++;
          isFirst = false;
        }
      }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
      return GetEnumerator();
    }
  }

  public struct Entry<T>
  {
    private readonly Position _position;
    private readonly T _value;
    private readonly int _index;

    public Position Position
    {
      get { return _position; }
    }

    public T Value
    {
      get { return _value; }
    }

    public int Index
    {
      get { return _index; }
    } 

    internal Entry(T value, int index, Position position)
    {
      _value = value;
      _index = index;
      _position = position;
    }
  }
}